@echo off
setlocal enabledelayedexpansion

REM Weather System Docker部署脚本 (Windows)

echo === Weather System Docker 部署脚本 ===

REM 检查Docker是否安装
docker --version >nul 2>&1
if errorlevel 1 (
    echo 错误: Docker未安装，请先安装Docker Desktop
    pause
    exit /b 1
)

docker-compose --version >nul 2>&1
if errorlevel 1 (
    echo 错误: Docker Compose未安装，请确保Docker Desktop已正确安装
    pause
    exit /b 1
)

REM 获取脚本参数
set ENVIRONMENT=%1
set BUILD_OPTION=%2

if "%ENVIRONMENT%"=="" set ENVIRONMENT=production
if "%BUILD_OPTION%"=="" set BUILD_OPTION=build

echo 部署环境: %ENVIRONMENT%
echo 构建选项: %BUILD_OPTION%

REM 设置docker-compose文件
if "%ENVIRONMENT%"=="development" (
    set COMPOSE_FILE=docker-compose.dev.yml
    echo 使用开发环境配置
) else if "%ENVIRONMENT%"=="production" (
    set COMPOSE_FILE=docker-compose.yml
    echo 使用生产环境配置
) else (
    echo 错误: 无效的环境参数，支持: development, production
    pause
    exit /b 1
)

REM 检查配置文件是否存在
if not exist "%COMPOSE_FILE%" (
    echo 错误: 配置文件 %COMPOSE_FILE% 不存在
    pause
    exit /b 1
)

REM 创建必要的目录
echo 创建必要的目录...
if not exist "logs" mkdir logs
if not exist "data" mkdir data
if not exist "monitoring\grafana\provisioning" mkdir monitoring\grafana\provisioning

REM 设置环境变量
echo 设置环境变量...
set COMPOSE_PROJECT_NAME=weather-system
set DOCKER_BUILDKIT=1

REM 停止现有服务
echo 停止现有服务...
docker-compose -f "%COMPOSE_FILE%" down --remove-orphans

REM 清理旧镜像(可选)
if "%BUILD_OPTION%"=="clean" (
    echo 清理旧镜像...
    docker system prune -f
    docker-compose -f "%COMPOSE_FILE%" build --no-cache
) else if "%BUILD_OPTION%"=="build" (
    echo 构建镜像...
    docker-compose -f "%COMPOSE_FILE%" build
)

REM 启动服务
echo 启动服务...
docker-compose -f "%COMPOSE_FILE%" up -d

REM 等待服务启动
echo 等待服务启动...
timeout /t 30 /nobreak >nul

REM 检查服务状态
echo 检查服务状态...
docker-compose -f "%COMPOSE_FILE%" ps

echo === 服务访问地址 ===
if "%ENVIRONMENT%"=="production" (
    echo 🌐 前端应用: http://localhost:3000
)
echo 🔧 API文档: http://localhost:5197/api-docs
echo 📊 Prometheus: http://localhost:9090
echo 📈 Grafana: http://localhost:3001 (admin/admin123)
echo 🐰 RabbitMQ管理: http://localhost:15672 (admin/admin123)
echo 🔍 Jaeger追踪: http://localhost:16686

echo === 部署完成 ===
echo 查看日志: docker-compose -f %COMPOSE_FILE% logs -f
echo 停止服务: docker-compose -f %COMPOSE_FILE% down

pause